package com.panda.cn.config.mvc;

import cn.hutool.core.util.StrUtil;
import com.panda.cn.config.exception.ReamException;
import com.panda.cn.config.permission.CheckPermission;
import com.panda.cn.config.permission.PermissionUtil;
import com.panda.cn.utils.jwt.JwtUtil;
import com.panda.cn.utils.jwt.WebContextUtil;
import com.panda.cn.utils.userAgent.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 登录处理程序拦截器
 *
 * @author Yanmh
 * @date 2022/09/14
 */
@Slf4j
public class loginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检验是否请求控制器
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String requestURI = request.getRequestURI();
        log.info(">>> 地址拦截: {}", requestURI);
        // 验证token
        String token = request.getHeader("token");
        
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否有LoginToken注释，有则跳过认证
        if (method.isAnnotationPresent(CheckPermission.class)) {
            CheckPermission checkPermission =  method.getAnnotation(CheckPermission.class);
            if (checkPermission.required()) {
                // 从 http 请求头中取出 permission
                String key = request.getParameter("key");
                // 权限为空
                if (StrUtil.isBlank(key)) {
                    JwtUtil.parseJWT(token); // 验证token
                } else {
                    String ip = UserAgentUtil.getIp(request);
                    // 权限不为空验证权限// 无异常则正常
                    PermissionUtil.verify(key, requestURI, ip);
                }
                return true;
            }
        }
        
        JwtUtil.parseJWT(token);
        //将token放入本地缓存
        WebContextUtil.setUserToken(token);
        return true;
    }
}
